const writeFile = require('./write-file');

module.exports = function (opts) {
    let ajax = '';
    let ajaxSetting = '';
    if (opts.data.ajax) {
        ajax = `
            import axios from 'axios';
            import env from '../config/env';
        `;
        ajaxSetting = `
            const ACTION_URL_DEV = 'http://www.url.com/';
            const ACTION_URL_PROD = 'http://www.url.com/';
            const ACTION_PATH_DEV = 'api';
            const ACTION_PATH_PROD= 'api';

            util.ajax = axios.create({
                baseURL: env === 'development' ? ACTION_URL_DEV:ACTION_URL_PROD,
                timeout: 30000
            });

            util.http_request=function(config){
                let f = config.post?util.ajax.post.bind(util.ajax):util.ajax.get.bind(util.ajax);
                config.data.rnd = Math.random()*100000;
                var d = {};
                if(config.post) d.data = config.data;
                else d.params = config.data;
                try{        
                    f(config.path || (env === 'development' ? ACTION_PATH_DEV:ACTION_PATH_PROD),d)
                    .then(function(res){
                        if(config.success)
                            config.success(res)
                    })
                    .catch(function(err){
                        if(config.failed)
                            config.failed(err)
                    });
                }catch(err){
                    if(config.failed)
                        config.failed(err)
                }
            };`;
    }

    const file = `
        ${ajax}
        let util = {

        };
        util.title = function (title) {
            title = title ? title + ' - Home' : 'iView project';
            window.document.title = title;
        };
        ${ajaxSetting}

        export default util;
    `;
    writeFile({
        directory: `${opts.directory}/src/libs`,
        fileName: 'util.js',
        data: file,
        success () {
            opts.success();
        },
        error () {
            opts.error();
        }
    });
};